﻿// <copyright file="Button.cs" company="DotNetLib">
//
// .netlib: http://www.codeplex.com/DotNetLib
//
// This code is released under the New BSD License.
// A copy of this license is available at:
// http://www.codeplex.com/DotNetLib/license
//
// </copyright>

namespace DotNetLib.Windows.Forms
{
  using System;
  using System.ComponentModel;
  using System.Drawing;
  using System.Runtime.InteropServices;
  using WF = System.Windows.Forms;

  /// <summary>
  /// A thin wrapper around the stock button control to provide images.
  /// </summary>
  public class Button : WF.Button
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="Button"/> class.
    /// </summary>
    public Button()
    {
      this.FlatStyle = WF.FlatStyle.System;
    }

    /// <summary>
    /// Gets or sets the image that is displayed on the button control.
    /// </summary>
    [Description("Gets or sets the image that is displayed on the button control."), Category("Appearance"), DefaultValue(null)]
    public new Image Image
    {
      get
      {
        return base.Image;
      }
      set
      {
        base.Image = value;
        this.UpdateImage();
      }
    }

    /// <summary>
    /// Gets or sets the <see cref="WF.FlatStyle"/> for the control.  This property is not meaningful for this control.
    /// </summary>
    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public new WF.FlatStyle FlatStyle
    {
      get { return base.FlatStyle; }
      set { base.FlatStyle = value; }
    }

    /// <summary>
    /// Updates the icon for the control.
    /// </summary>
    private void UpdateImage()
    {
      if ((this.Image as Bitmap) != null)
      {
        HandleRef handle = new HandleRef(this, Handle);
        IntPtr iconHandle = (this.Image as Bitmap).GetHicon();
        NativeMethods.SendMessage(handle, NativeMethods.BM_SETIMAGE, new IntPtr(1), iconHandle);
      }
    }
  }
}
